package com.north.light.libcommon.recyclerview;


import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;


/**
 * 滑动加载更多的recyclerview
 * 滑动到底部就会触发加载监听
 */
public abstract class LoadMoreRecyclerView extends RecyclerView {
    private Handler mUiHandler;
    private OnScrollLastItem onScrollLastItem;
    // 最后几个完全可见项的位置（瀑布式布局会出现这种情况）
    private int[] lastVisiblePosition;
    // 最后一个完全可见项的位置
    private int lastItemPosition;
    //用户是否滑动过的标识
    private volatile boolean isScrollTAG = false;

    //加载更多开关的标识
    private volatile boolean openSwitch = true;

    public LoadMoreRecyclerView(Context context) {
        super(context);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    public void onChildDetachedFromWindow(View child) {
        super.onChildDetachedFromWindow(child);
    }

    private void init() {
        if (mUiHandler == null) {
            mUiHandler = new Handler();
        }
        addOnScrollListener(new AutoLoadScrollListener());
    }


    public class AutoLoadScrollListener extends OnScrollListener {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LayoutManager layoutManager = recyclerView.getLayoutManager();
            // 找到最后一个完全可见项的位置
            if (layoutManager instanceof StaggeredGridLayoutManager) {
                StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) layoutManager;
                if (lastVisiblePosition == null) {
                    lastVisiblePosition = new int[manager.getSpanCount()];
                }
                manager.findLastCompletelyVisibleItemPositions(lastVisiblePosition);
                lastItemPosition = getMaxPosition(lastVisiblePosition);
            } else if (layoutManager instanceof GridLayoutManager) {
                lastItemPosition = ((GridLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
            } else if (layoutManager instanceof LinearLayoutManager) {
                lastItemPosition = ((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
            } else {
                throw new RuntimeException("Unsupported LayoutManager.");
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState) {
                case SCROLL_STATE_IDLE:
                    LayoutManager layoutManager = recyclerView.getLayoutManager();
                    //通过比对 最后完全可见项位置 和 总条目数，来判断是否滑动到底部
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    if (visibleItemCount > 0 && lastItemPosition >= totalItemCount - 1 && !isScrollTAG) {
                        isScrollTAG = true;
                        if (onScrollLastItem != null && openSwitch) {
                            onScrollLastItem.ScrollToBottom();
                        }
                    }
                    break;
                case SCROLL_STATE_DRAGGING:

                    break;
                case SCROLL_STATE_SETTLING:
                    break;
            }
        }
    }

    private int getMaxPosition(int[] positions) {
        int max = positions[0];
        for (int i = 1; i < positions.length; i++) {
            if (positions[i] > max) {
                max = positions[i];
            }
        }
        return max;
    }

    //设置多少毫秒后可以再次滑动
    public void setCanLoadDelay(long time) {
        if (mUiHandler != null) {
            mUiHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isScrollTAG = false;
                }
            }, time);
        } else {
            isScrollTAG = false;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        if (mUiHandler != null) {
            mUiHandler.removeCallbacksAndMessages(null);
        }
        mUiHandler = null;
        removeOnScrollLastItemListener();
        super.onDetachedFromWindow();

    }

    public void switchLoadMore(boolean isOpen) {
        this.openSwitch = isOpen;
    }

    //滚动到最后一项的监听
    public interface OnScrollLastItem {
        void ScrollToBottom();
    }

    public void setOnScrollLastItemListener(OnScrollLastItem onScrollLastItem) {
        this.onScrollLastItem = onScrollLastItem;
    }

    public void removeOnScrollLastItemListener() {
        this.onScrollLastItem = null;
    }
}
